<template>
    <el-form
        v-if="schema && schema.properties"
        :inline="true"
        class="schema-search-bar"
    >
        <el-form-item
            v-for="(item, index) in schema.properties"
            :key="index"
            :label="item.label"
        >
            <component
                :ref="el => setItemRef(el, index)"
                :is="SearchItemConfig[item.option?.comType]?.component"
                :schemaKey="index"
                :schema="item"
                @loaded="handleChildLoaded"
            ></component>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" plain class="search-btn" @click="search">查询</el-button>
            <el-button plain class="reset-btn" @click="reset">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { onMounted, ref, toRefs } from 'vue';
import SearchItemConfig from './search-item-config.js';

const props = defineProps({
    /**
     * schema 配置
     * "type": "object",
        "properties": {
            "key": {
                // ...标准schema配置
                "type": "",  // 字段类型
                "label": "", // 字段中文名
                "searchOption": {
                    // "...elComponentConfig", 标准elComponentConfig配置
                    "comType": "el-input",//配置组件类型 input/select/el-date-picker/...
                    "default": ""
                }
            }
            // ...其他字段
        }
    */
    schema: Object
})
onMounted(() => { 
    console.log(schema.value,'111111');  
    console.log(SearchItemConfig['input'].component,'.4555555555');
    
})
const { schema } = toRefs(props)

const emit = defineEmits(['load','search','reset'])

// 使用Map存储子组件引用
const searchItemRefs = ref(new Map())

// 设置子组件引用的函数
const setItemRef = (el, index) => {
  if (el) {
    searchItemRefs.value.set(index, el)
  }
}

const getValue = () => {
    let dtoObj = {}
    // 从Map中获取所有子组件引用
    searchItemRefs.value.forEach(el => {
        dtoObj = {...dtoObj, ...el?.getValue()}
    })
    console.log(dtoObj, 'dtoObj');
    
    return dtoObj
}

let childComLoadedCount = 0
const handleChildLoaded = () => { 
    childComLoadedCount++
    if (childComLoadedCount >= Object.keys(schema?.value?.properties).length) {
        emit('load', getValue())
    }
}
const search = () => { 
    emit('search', getValue())
}

const reset = () => { 
    searchItemRefs.value.forEach(el => { 
        el?.reset()
    })
    emit('reset')
}

defineExpose({
    reset,
    getValue
})

</script>

<style lang="less">
.schema-search-bar {
    min-width: 500px;

    .input {
        width: 180px;
    }

    .select {
        width: 180px;
    }

    .date-range { 
        width: 300px;
    }

    .search-btn {
        width: 100px;
    }

    .reset-btn {
        width: 100px;
    }
}
</style>